package com.vision.util.http.param;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhongchao
 * @title
 * @date 2017-08-22
 * @since v1.0.0
 */
public class PostParams extends HttpRequestParams<PostParams> {

    private String json;

    public PostParams(String url, String charset) {
        super(url, charset);
    }

    public PostParams(String url, String charset, String json) {
        super(url, charset);
    }

    @Override
    public HttpRequestBase build() throws IOException {
        HttpPost post = new HttpPost(url);
        headers.forEach(post::addHeader);
        List<NameValuePair> formParams = new ArrayList<>(params.size());
        params.forEach((k, v) -> formParams.add(new BasicNameValuePair(k, v)));
        post.setEntity(new UrlEncodedFormEntity(formParams, charset));
        return post;
    }

    HttpRequestBase build_json() throws IOException {
        HttpPost post = new HttpPost(url);
        headers.forEach(post::addHeader);
        StringEntity entity = new StringEntity(json);
        entity.setContentEncoding(charset);
        entity.setContentType("application/json");
        post.setEntity(entity);
        return post;
    }
}
